#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#define SERVER_IP "192.168.164.98"
#define SERVER_PORT 8080


//添加注释
int main(int argc, char *argv[])
{
    struct sockaddr_in server_addr = {0};
    // struct sockaddr_in client_addr = {0};

    // char ip_str[20] = {0};
    int socket_fd; // connect_fd;
                   //  int addrlen = sizeof(client_addr);
    char buf[512];
    int ret;

    // 1- 打开套接字，得到套接字描述符
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0)
    {
        perror("socket error");
        exit(EXIT_FAILURE);
    }
    // 2- 将套接字与指定端口号进行绑定
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);

    ret = connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    if (ret < 0)
    {
        perror("connect error");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }

    printf("server get success ...\n");

    // 5-  接收客户端发送过来的数据
    while (1)
    {
        // 接收缓冲区清零
        memset(buf, 0x0, sizeof(buf));

        // 接收用户输入的字符串数据
        printf("Please enter a string: ");
        fgets(buf, sizeof(buf), stdin);

        // 将用户输入的数据发送给服务器
        ret = send(socket_fd, buf, strlen(buf), 0);
        if (0 > ret)
        {
            perror("send error");
            break;
        }
        //输入了"exit"，退出循环
        if (0 == strncmp(buf, "exit", 4))
            break;
    }

    // 6- 关闭套接字
    close(socket_fd);
    exit(EXIT_SUCCESS);
}